#!/bin/bash

run_user=`whoami`

if [ 'X'$run_user != 'X''root' ]
then
    echo 'Error! should run me with root...'
    exit 1
fi

# absolute path of openresty tarball used. if not give, will download openresty tarball from Internet
TARBALL_PATH=''

# absolute path to install openresty
INSTALL_HOME=''


usage() { 
  echo -e "
Usage:
  $0 [-f ARCHIVE_TARBARR_PATH] [-h INSTALL_HOME]
Common options:
  -f,  file, absolute path of archive tarball. Without -f options will download tarball from Internet
  -h,  home, absolute path of php install path, default to "'`/usr/local/openresty`'"
" 1>&2; exit 1;
}

while getopts ":f:h:" o; do
    case "${o}" in
        f)
            v=${OPTARG}
            if [ 'X'$v == 'X' ]
            then
              usage
            else
              TARBALL_PATH=${OPTARG}
            fi
            ;;
        h)
            v=${OPTARG}
            if [ 'X'$v == 'X' ]
            then
              usage
            else
              INSTALL_HOME=${OPTARG}
            fi
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))


if [ 'X'${TARBALL_PATH} == 'X' ]
then
    # version used when no tarball give
    DEFAULT_VERSION=1.21.4.3

    tarball="openresty-${DEFAULT_VERSION}.tar.gz"
    TARBALL_PATH="/tmp/${tarball}"

    if [ -f ${TARBALL_PATH} ]
    then
        rm -rf ${TARBALL_PATH}
    fi
    echo "not give nginx tarball absolute path, will download ${tarball} from Internet"
    # https://openresty.org/download/openresty-1.21.4.3.tar.gz
    curl https://openresty.org/download/${tarball} --output ${TARBALL_PATH}
fi
if [ ! -f ${TARBALL_PATH} ]
then
    echo "ERROR! openresty tarball:${TARBALL_PATH} not found, exit..."
    exit 11
fi

if [ 'X'${INSTALL_HOME} == 'X' ]
then
    INSTALL_HOME='/usr/local/openresty'
    echo "not give openresty install home absolute path, will use default path: ${INSTALL_HOME}"
fi
if [ -d ${INSTALL_HOME} ]
then
    echo "ERROR! openresty home:${INSTALL_HOME} exists, exit..."
    exit 10
fi


remove_openresty_centos(){
    cd /
    # stop nginx process
    systemctl disable nginx.service 
    systemctl stop nginx.service 
    
    # remove nginx* with yum
    yum remove *nginx* -y
    yum remove *openresty* -y

    rm -f /etc/systemd/system/nginx.service
    systemctl daemon-reload
    
    # del previous nginx user
    userdel nginx
    groupdel nginx
}

remove_openresty_ubuntu(){
    cd /
    # stop nginx process
    systemctl disable nginx.service 
    systemctl stop nginx.service 
    
    # remove nginx* with apt-get
    apt-get remove *nginx* -y
    apt-get remove *openresty* -y

    rm -f /etc/systemd/system/nginx.service
    systemctl daemon-reload
    
    # del previous nginx user
    userdel nginx
    groupdel nginx
}

install_libs_centos(){
    cd /
    yum update -y
    # install gcc, g++, make and libs
    yum install gcc gcc-c++ make pcre-devel openssl-devel zlib-devel -y
    
}

install_libs_ubuntu(){
    cd /
    apt-get update -y
    # install gcc, g++ and make
    apt-get install build-essential make perl libpcre3-dev libssl-dev curl zlib1g-dev -y 
}

is_centos=`awk -F '=' '/PRETTY_NAME/ { print $2 }' /etc/os-release | grep -i centos | wc -l`
is_ubuntu=`awk -F '=' '/PRETTY_NAME/ { print $2 }' /etc/os-release | grep -i ubuntu | wc -l`


if [ $is_centos -gt 0 ]
then
    # stop nginx process, and del previous nginx user
    remove_openresty_centos
    # install libs
    install_libs_centos
    # create user nginx:nginx
    adduser nginx --system --no-create-home --shell /bin/false --user-group
fi

if [ $is_ubuntu -gt 0 ]
then
    # stop nginx process, and del previous nginx user
    remove_openresty_ubuntu
    # install libs
    install_libs_ubuntu
    # create user nginx:nginx
    adduser nginx --system --no-create-home --shell /bin/false --group
fi


cd /tmp
if [ -d /tmp/openresty_packages ]
then
    rm -rf /tmp/openresty_packages
fi

mkdir -p /tmp/openresty_packages

if [ -d ${INSTALL_HOME} ]
then
    rm -rf ${INSTALL_HOME}
fi
mkdir -p ${INSTALL_HOME}

chmod -R 755 ${INSTALL_HOME}

cd /tmp/openresty_packages
tar -xzvf ${TARBALL_PATH} -C /tmp/openresty_packages --strip-components 1

make distclean

./configure -j2

make install

# exit with error if make nginx fail
ret=$?

if [ 'X'$ret != 'X'0 ]
then
    make distclean
    rm -rf /tmp/openresty_packages
    echo 'Error! make openresty failed...'
    exit 9
fi

${INSTALL_HOME}/nginx/sbin/nginx -V

rm -rf /tmp/openresty_packages

# add ln for "nginx"
if [ -e /usr/bin/nginx -o -L /usr/bin/nginx ]
then
    rm -rf /usr/bin/nginx
fi
ln -s ${INSTALL_HOME}/nginx/sbin/nginx /usr/bin/nginx


echo "
[Unit]
Description=The openresty HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=${INSTALL_HOME}/nginx/logs/nginx.pid
# Nginx will fail to start if /var/run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running `nginx -t` from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
ExecStartPre=/bin/rm -f ${INSTALL_HOME}/nginx/logs/nginx.pid
ExecStartPre=${INSTALL_HOME}/nginx/sbin/nginx -t
ExecStart=${INSTALL_HOME}/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=mixed
PrivateTmp=true

[Install]
WantedBy=multi-user.target
" > /etc/systemd/system/nginx.service


rm -rf /tmp/openresty_packages

echo "openresty installed in ${INSTALL_HOME}, and nginx installed in ${INSTALL_HOME}/nginx, conf file in ${INSTALL_HOME}/nginx/conf and log in ${INSTALL_HOME}/nginx/logs"

systemctl daemon-reload
systemctl enable nginx.service 
systemctl start nginx

echo "nginx start and will automatically start on boot, use 'systemctl status nginx' to check"